/*
 *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.base.util.handler;

import cn.hutool.core.lang.tree.Tree;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.util.DefaultInstantiatorStrategy;
import com.iwindplus.base.util.domain.dto.DataTransDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.objenesis.strategy.StdInstantiatorStrategy;

/**
 * kryo对象池工厂.
 *
 * @author zengdegui
 * @since 2025/11/08 12:07
 */
@Slf4j
public class PooledKryoFactory extends BasePooledObjectFactory<Kryo> {

    @Override
    public Kryo create() throws Exception {
        Kryo kryo = new Kryo();
        // 无循环引用时关闭
        kryo.setReferences(true);
        // 提前注册
        kryo.setRegistrationRequired(false);
        // Kryo 5.5+ 专用，性能提升明显
        kryo.setOptimizedGenerics(true);
        // 归还池时自动 reset
        kryo.setAutoReset(true);
        // 实例化策略：反射 → Unsafe → 空构造器 三级兜底
        DefaultInstantiatorStrategy strategy = new DefaultInstantiatorStrategy(
            new StdInstantiatorStrategy());
        kryo.setInstantiatorStrategy(strategy);
        kryo.register(DataTransDTO.class, 100);
        kryo.register(Tree.class, 101);
        log.info("Kryo对象池创建成功");
        return kryo;
    }

    @Override
    public PooledObject<Kryo> wrap(Kryo kryo) {
        return new DefaultPooledObject<>(kryo);
    }

    @Override
    public void passivateObject(PooledObject<Kryo> p) {
        p.getObject().reset();
    }
}
